(function() {

	var appModule = angular.module('tracecashModule');

	appModule.directive('capitalize', function() {
		return {
			require : 'ngModel',
			link : function(scope, element, attrs, modelCtrl) {
				var capitalize = function(inputValue) {
					if (inputValue == undefined)
						inputValue = '';
					var capitalized = inputValue.toUpperCase();
					if (capitalized !== inputValue) {
						modelCtrl.$setViewValue(capitalized);
						modelCtrl.$render();
					}
					return capitalized;
				};
				modelCtrl.$parsers.push(capitalize);
				capitalize(scope[attrs.ngModel]); // capitalize initial value
			}
		};
	});

	appModule.directive('account', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/components/account.html',
			require : '^ngModel',
			scope : {
				account : '=ngModel'
			},
		};
	});

	appModule.directive('calendar', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/components/calendar.html',
			controller : 'CalendarCtrl',
			require : '^ngModel',
			replace : 'true',
			scope : {
				ngModel : '=',
				disabled : '@'
			},
		};
	});

	appModule.directive('searchResultPagination', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/components/search-result-pagination.html',
			replace : 'false'
		};
	});

	appModule.controller('TotalResultsPaginationCtrl', ['$scope', function($scope) {
		$scope.$watch('searchResults.currentPage', function() {
			if ($scope.searchResults != null) {
				if ($scope.searchResults.totalResults == null) {
					$scope.searchResults.totalResults = angular.copy($scope.searchResults.results);
					$scope.searchResults.results = [];
				}
				var begin = (($scope.searchResults.currentPage - 1) * $scope.searchResults.itemsPerPage), end = begin + $scope.searchResults.itemsPerPage;
				$scope.searchResults.results = $scope.searchResults.totalResults.slice(begin, end);
			}
			$scope.setPage = function(page) {
			};
		});
	}]);

	appModule.directive('messageErrorPanel', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/components/message-error-panel.html',
			controller : ['$scope', '$timeout', function($scope, $timeout) {
				$scope.$watch('message', function() {
					$scope.isCollapse = false;
				});
				$scope.setCollapse = function() {
					$scope.isCollapse = true;
				};
				if ($scope.autoClose) {
					$scope.$watch('message', function(newValue, oldValue) {
						$timeout(function() {
							$scope.isCollapse = true;
						}, 5000);
					});
				}
			}],
			require : '^ngModel',
			replace : 'false',
			scope : {
				message : '=ngModel',
				autoClose : '='
			},
		};
	});

	appModule.directive('messageErrorBox', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/components/message-error-box.html',
			controller : ['$scope', function($scope) {
				$scope.$watch('messages', function() {
					$scope.isCollapse = false;
				});
				$scope.setCollapse = function() {
					$scope.isCollapse = true;
				};
			}],
			require : '^ngModel',
			replace : 'false',
			scope : {
				messages : '=ngModel',
				messageIcon : '@',
				messageClass : '@'
			}
		};
	});

	appModule.factory('MessageUtils', function() {
		return {
			createError : function(text) {
				var message = new Object();
				message.errors = new Array();
				message.errors[0] = new Object();
				message.errors[0].text = text;
				return message;
			}
		};
	});

	appModule.factory('Utils', function() {
		return {
			isEmpty : function(value) {
				return value == null || value == '' || value == 'undefined';
			}
		};
	});

	appModule.directive('amount', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/components/amount.html',
			require : '^ngModel',
			replace : 'true',
			scope : {
				ngChange : '=',
				ngModel : '=',
				disabled : '@'
			},
			link : function(scope) {
				scope.$watch('ngModel', function(newValue, oldValue) {
					var arr = String(newValue).split("");
					if (arr.length === 0)
						return;
					if (arr.length === 1 && arr[0] == '-')
						return;
					if (newValue != null && isNaN(newValue)) {
						scope.ngModel = oldValue != null ? oldValue : 0;
					}
				});
			}
		};
	});

	appModule.directive('number', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/components/number.html',
			require : '^ngModel',
			replace : 'true',
			scope : {
				ngChange : '=',
				ngModel : '=',
				disabled : '@'
			},
			link : function(scope) {
				scope.$watch('ngModel', function(newValue, oldValue) {
					var arr = String(newValue).split("");
					if (arr.length === 0)
						return;
					if (arr.length === 1 && arr[0] == '-')
						return;
					if (newValue != null && isNaN(newValue)) {
						scope.ngModel = oldValue != null ? oldValue : 0;
					}
				});
			}
		};
	});

	appModule.directive('percent', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/components/percent.html',
			require : '^ngModel',
			replace : 'false',
			scope : {
				ngChange : '=',
				ngModel : '=',
				disabled : '@'
			},
			link : function(scope) {
				scope.$watch('ngModel', function(newValue, oldValue) {
					var arr = String(newValue).split("");
					if (arr.length === 0)
						return;
					if (arr.length === 1 && arr[0] == '-')
						return;
					if (newValue != null && isNaN(newValue)) {
						scope.ngModel = oldValue != null ? oldValue : 0;
					} else if (scope.ngModel > 100) {
						scope.ngModel = 100;
					} else if (scope.ngModel < 0) {
						scope.ngModel = 0;
					}
				});
			}
		};
	});

	appModule.directive('country', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/components/country.html',
			require : '^ngModel',
			controller : 'CountryCtrl',
			replace : 'false',
			scope : {
				country : '=ngModel'
			}
		};
	});

	appModule.directive('reserve', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/components/reserve.html',
			require : '^ngModel',
			controller : 'ReserveCtrl',
			replace : 'false',
			scope : {
				sinister : '=ngModel',
				canChangeReserve : '@',
				showReserveVariation : '@'
			}
		};
	});

	appModule.directive('selectEnum', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/components/select-enum.html',
			require : [ '^ngModel', '^enumName' ],
			controller : ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http) {
				$http.get($rootScope.REST_PATH + '/sinisterEnum/' + $scope.enumName, {
					cache : true
				}).success(function(data) {
					$scope.names = data;
				});
			}],
			scope : {
				ngModel : '=',
				ngDisabled : '=',
				enumName : '@'
			}
		};
	});

	appModule.directive('backButton', ['$window', function($window) {
		return {
			restrict : 'AE',
			template : '<button class="btn btn-primary" translate="back"></button>',
			link : function(scope, element, attrs) {
				element.on('click', function() {
					$window.history.back();
				});
			}
		};
	}]);

	appModule.controller('ReserveCtrl', ['$scope', '$rootScope', '$timeout', '$http', '$modal', function($scope, $rootScope, $timeout, $http, $modal) {
		$scope.reserveVariation = function() {
			$modal.open({
				templateUrl : 'html/components/reserve-variation.html',
				controller : 'ReserveVariationCtrl',
				size : 'lg',
				resolve : {
					sinisterId : function() {
						return $scope.sinister.id;
					}
				}
			});
		};
		$scope.changeReserve = function(type) {
			var amount = (type == 'NORMAL') ? $scope.sinister.sinisterInfo.currentReserveVariation : $scope.sinister.sinisterInfo.feesReserveVariation;
			return $http.get($rootScope.REST_PATH + "/reservevariation/saveVariation/" + $scope.sinister.id + "/" + type + "/" + amount, {}).success(function(data) {
				$scope.message = data;
				$scope.sinister.sinisterInfo = data.payload;
			});
		};
		$scope.$watch('sinister.sinisterInfo.currentReserve + sinister.sinisterInfo.feesReserve', function(total) {
			$scope.sinister.sinisterInfo.totalReserve = total;
		});
	}]);

	appModule.controller('ReserveVariationCtrl', ['$scope', '$rootScope', '$http', '$modalInstance', 'sinisterId', function($scope, $rootScope, $http, $modalInstance, sinisterId) {
		$scope.searchResults = {};
		$scope.sinisterId = sinisterId;
		$scope.setPage = function(page) {
			$scope.currentPage = page;
			$http.get($rootScope.REST_PATH + '/reservevariation/find/' + $scope.sinisterId, {
				params : {
					p : $scope.currentPage,
					n : $rootScope.PAGE_SIZE
				}
			}).success(function(data) {
				$scope.searchResults = data;
			});
		};
		$scope.setPage(1);
		$scope.cancel = function() {
			$modalInstance.dismiss('cancel');
		};
	}]);

	appModule.controller('CountryCtrl', ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http) {
		$scope.selected = undefined;
		$scope.getCountries = function(val) {
			return $http.get($rootScope.REST_PATH + '/country/like/' + val, {}).then(function(res) {
				var countries = [];
				angular.forEach(res.data, function(item) {
					countries.push(item);
				});
				return countries;
			});
		};
	}]);

	appModule.directive('province', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/components/province.html',
			require : '^ngModel',
			controller : 'ProvinceCtrl',
			replace : 'true',
			scope : {
				ngModel : '='
			}
		};
	});

	appModule.directive('locality', function() {
		return {
			restrict : 'AE',
			templateUrl : 'html/components/locality.html',
			require : '^ngModel',
			controller : 'LocalityCtrl',
			replace : 'true',
			scope : {
				ngModel : '=',
				provinceId : '='
			}
		};
	});

	appModule.controller('LocalityCtrl', ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http) {
		$scope.selected = undefined;
		$scope.getLocalities = function(val) {
			return $http.get($rootScope.REST_PATH + '/locality/like/' + val, {
				params : {
					p : 1,
					n : $rootScope.SEARCH_PAGE_SIZE,
					provinceId : $scope.provinceId
				}

			}).then(function(res) {
				var localities = [];
				angular.forEach(res.data, function(item) {
					localities.push(item);
				});
				return localities;
			});
		};
	}]);

	appModule.controller('ProvinceCtrl', ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http) {
		$scope.selected = undefined;
		$scope.getProvinces = function(val) {
			return $http.get($rootScope.REST_PATH + '/province/like/' + val, {}).then(function(res) {
				var provinces = [];
				angular.forEach(res.data, function(item) {
					provinces.push(item);
				});
				return provinces;
			});
		};
	}]);

	appModule.controller('CalendarCtrl', ['$scope', function($scope) {
		$scope.today = function() {
			$scope.ngModel = new Date();
		};
		$scope.clear = function() {
			$scope.ngModel = null;
		};
		$scope.toggleMin = function() {
			$scope.minDate = $scope.minDate ? null : new Date();
		};
		$scope.toggleMin();

		$scope.showCalendar = false;
		$scope.open = function($event) {
			$scope.showCalendar = true;
			$event.preventDefault();
			$event.stopPropagation();
			$scope.opened = true;
		};

		$scope.dateOptions = {
			formatYear : 'yy',
			startingDay : 1
		};

		$scope.formats = [ 'dd/MM/yyyy', 'dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate' ];
		$scope.format = $scope.formats[0];
	}]);

})();